<template>
  <div class="app-container">
    <!-- 左右布局容器 -->
    <div class="layout-row">
      <!-- 左侧分类树 -->
      <div class="left-tree">
        <div class="tree-header">合同分类</div>
        <el-tree
            ref="contractTree"
            :data="treeData"
            :props="treeProps"
            @node-click="handleTreeSelect"
            default-expand-all
            node-key="id"
            highlight-current
        />
      </div>

      <!-- 右侧内容区 -->
      <div class="right-content">
        <!-- 顶部操作栏 -->
        <div class="top-bar">
          <el-input
              v-model="queryParams.employeeName"
              placeholder="请输入员工姓名"
              clearable
              class="search-input"
              @keyup.enter="getList"
          />
          <el-button type="primary" icon="Search" @click="getList">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          <!-- 保留批量删除按钮，删除上传合同按钮 -->
          <el-button
              type="danger"
              icon="Delete"
              :disabled="!selectedRows.length"
              @click="handleBatchDelete"
              v-hasPermi="['contract:contract:batchRemove']"
          >批量删除</el-button>
        </div>

        <!-- 表格操作按钮 -->
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
                type="primary"
                plain
                icon="Plus"
                @click="handleAdd"
                v-hasPermi="['contract:contract:add']"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
                type="success"
                plain
                icon="Edit"
                :disabled="selectedRows.length !== 1"
                @click="handleUpdate"
                v-hasPermi="['contract:contract:edit']"
            >修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <!-- 保留单个删除按钮 -->
            <el-button
                type="danger"
                plain
                icon="Delete"
                :disabled="!selectedRows.length"
                @click="handleDelete"
                v-hasPermi="['contract:contract:remove']"
            >删除</el-button>
          </el-col>
        </el-row>

        <!-- 合同表格 -->
        <el-table
            v-loading="loading"
            :data="contractList"
            @selection-change="handleSelection"
            border
            style="width: 100%"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="合同名称" align="center" prop="contractName" />
          <el-table-column label="合同编号" align="center" prop="contractNumber" />
          <el-table-column label="所属部门" align="center" prop="deptName" />
          <el-table-column label="员工姓名" align="center" prop="employeeName" width="170" />
          <el-table-column label="合同开始日期" align="center" prop="startDate" width="170">
            <template #default="scope">
              <span>{{ formatDate(scope.row.startDate) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="合同结束日期" align="center" prop="endDate" width="170">
            <template #default="scope">
              <span>{{ formatDate(scope.row.endDate) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="300px" class-name="operation-column">
            <template #default="scope">
              <!-- 优化后的操作按钮样式 -->
              <el-button
                  size="small"
                  type="text"
                  icon="Edit"
                  @click="handleUpdate(scope.row)"
                  v-hasPermi="['contract:contract:edit']"
                  class="operation-btn edit-btn"
              >编辑</el-button>

              <el-button
                  size="small"
                  type="text"
                  icon="Delete"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['contract:contract:remove']"
                  class="operation-btn delete-btn"
              >删除</el-button>

              <!-- 修复后的上传按钮 -->
              <el-upload
                  size="small"
                  type="text"
                  :action="uploadUrl"
                  :on-success="(res) => handleAvatarSuccess(res, scope.row.id)"
                  :before-upload="beforeAvatarUpload"
                  :auto-upload="false"
                  :data="{ contractId: scope.row.id }"
                  class="operation-btn upload-btn"
                  :show-file-list="false"
              >
                <template #trigger>
                  <span class="el-icon-upload2"></span>
                  <span>上传</span>
                </template>
              </el-upload>

              <el-button
                  size="small"
                  type="text"
                  icon="Download"
                  @click="handleDownload(scope.row)"
                  v-hasPermi="['contract:contract:download']"
                  class="operation-btn download-btn"
              >下载</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <pagination
            v-show="total > 0"
            :total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="getList"
        />
      </div>
    </div>

    <!-- 新增/编辑弹窗 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="500px" append-to-body>
      <el-form ref="contractForm" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="合同编号" prop="contractNumber">
          <el-input v-model="form.contractNumber" placeholder="请输入合同编号" />
        </el-form-item>
        <el-form-item label="合同开始日期" prop="startDate">
          <el-date-picker
              clearable
              v-model="form.startDate"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择合同开始日期"
          />
        </el-form-item>
        <el-form-item label="合同结束日期" prop="endDate">
          <el-date-picker
              clearable
              v-model="form.endDate"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择合同结束日期"
          />
        </el-form-item>
        <el-form-item label="公司ID" prop="companyId">
          <el-input v-model="form.companyId" placeholder="请输入公司ID" />
        </el-form-item>
        <el-form-item label="合同有效期" prop="validityPeriod">
          <el-input v-model="form.validityPeriod" placeholder="如：3年" />
        </el-form-item>
        <el-form-item label="合同签订日期" prop="signingDate">
          <el-date-picker
              clearable
              v-model="form.signingDate"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择合同签订日期"
          />
        </el-form-item>
        <el-form-item label="合同附录内容" prop="appendix">
          <el-input v-model="form.appendix" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="备注信息" prop="remarks">
          <el-input v-model="form.remarks" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="合同类别ID" prop="categoryId">
          <el-input v-model="form.categoryId" placeholder="请输入合同类别ID" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="dialogVisible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import {
  listContract,
  getContract,
  delContract,
  addContract,
  updateContract,
  contractCategoryList
} from '@/api/contract/contract'
import Pagination from '@/components/Pagination/index.vue'

// 分类树数据
const treeData = ref([])
const treeProps = { children: 'children', label: 'label' }
const contractTree = ref(null) // 树组件引用

// 表格数据
const contractList = ref([])
const loading = ref(false)
const total = ref(0)
const selectedRows = ref([])

// 查询参数，默认选中“企业合同”
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  employeeName: '',
  parentContractName: '企业合同', // 默认父合同分类
  contractName: ''
})

// 弹窗相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const form = reactive({})
const rules = reactive({
  contractNumber: [{ required: true, message: '请输入合同编号', trigger: 'blur' }],
  contractName: [{ required: true, message: '请输入合同名称', trigger: 'blur' }],
  startDate: [{ required: true, message: '请选择合同开始日期', trigger: 'change' }],
  endDate: [{ required: true, message: '请选择合同结束日期', trigger: 'change' }],
})

// 上传URL
const uploadUrl = ref('http://localhost/dev-api/oss/upload')

/** 初始化 */
onMounted(() => {
  getCategoryList()
})

/** 获取合同分类列表 */
function getCategoryList() {
  contractCategoryList().then(res => {
    if (res.contractCategory) {
      // 格式化树形数据
      treeData.value = Object.entries(res.contractCategory).map(([parent, children]) => ({
        id: `parent_${parent}`,
        label: parent,
        children: children.map(child => ({
          id: `child_${parent}_${child}`,
          label: child
        }))
      }))

      // 使用 nextTick 确保树组件已渲染完成
      nextTick(() => {
        const enterpriseNode = treeData.value.find(node => node.label === '企业合同')
        if (enterpriseNode) {
          contractTree.value.setCurrentKey(enterpriseNode.id) // 设置选中节点
          getList() // 加载默认分类数据
        } else {
          ElMessage.warn('未找到“企业合同”分类')
        }
      })
    }
  }).catch(error => {
    ElMessage.error('加载合同分类失败')
  })
}

/** 获取合同列表 */
function getList() {
  loading.value = true
  listContract(queryParams).then(res => {
    contractList.value = res.rows || []
    total.value = res.total || 0
  }).catch(error => {
    ElMessage.error('获取合同列表失败')
  }).finally(() => {
    loading.value = false
  })
}

/** 树节点点击事件 */
function handleTreeSelect(node) {
  queryParams.parentContractName = node.children?.length ? node.label : ''
  queryParams.contractName = node.children?.length ? '' : node.label
  queryParams.pageNum = 1 // 重置页码
  getList() // 重新加载数据
}

/** 重置查询 */
function resetQuery() {
  queryParams.employeeName = ''
  queryParams.pageNum = 1
  // 保持默认“企业合同”分类
  queryParams.parentContractName = '企业合同'
  queryParams.contractName = ''

  // 重新选中节点
  nextTick(() => {
    const enterpriseNode = treeData.value.find(node => node.label === '企业合同')
    if (enterpriseNode) {
      contractTree.value.setCurrentKey(enterpriseNode.id)
    }
  })

  getList()
}

/** 表格选择事件 */
function handleSelection(rows) {
  selectedRows.value = rows
}

// 保留批量删除和单个删除函数
function handleBatchDelete() {
  const ids = selectedRows.value.map(item => item.id).join(',')
  ElMessageBox.confirm(
      `是否确认删除选中的【${selectedRows.value.length}条】合同?`,
      '提示',
      { type: 'warning' }
  ).then(() => {
    delContract(ids).then(() => {
      ElMessage.success('批量删除成功！')
      getList()
    })
  })
}

function handleDelete(row) {
  ElMessageBox.confirm(
      `是否确认删除合同【${row.contractName}】?`,
      '提示',
      { type: 'warning' }
  ).then(() => {
    delContract(row.id).then(() => {
      ElMessage.success('删除成功！')
      getList()
    })
  })
}

// 新增合同
function handleAdd() {
  dialogTitle.value = '新增合同'
  // 清空表单
  Object.assign(form, {
    id: null,
    contractNumber: '',
    contractName: '',
    startDate: '',
    endDate: '',
    companyId: '',
    validityPeriod: '',
    signingDate: '',
    appendix: '',
    remarks: '',
    categoryId: ''
  })
  dialogVisible.value = true
}

// 修改合同
function handleUpdate(row) {
  dialogTitle.value = '修改合同'
  Object.assign(form, row)
  dialogVisible.value = true
}

// 提交表单
function submitForm() {
  contractForm.value.validate(valid => {
    if (valid) {
      const api = form.id ? updateContract : addContract
      api(form).then(res => {
        if (res.code === 200) {
          ElMessage.success(form.id ? '修改成功' : '新增成功')
          dialogVisible.value = false
          getList()
        } else {
          ElMessage.error(res.msg || (form.id ? '修改失败' : '新增失败'))
        }
      }).catch(error => {
        ElMessage.error('操作失败，请稍后重试')
      })
    }
  })
}

// 下载文件
function handleDownload(row) {
  if (!row.fileUrl) {
    ElMessage.warning('该合同没有关联文件')
    return
  }
  // 实际项目中应该使用合适的方式下载文件
  window.open(row.fileUrl, '_blank')
}

// 日期格式化函数
function formatDate(date) {
  if (!date) return '--'
  try {
    const d = new Date(date)
    return d.toISOString().split('T')[0]
  } catch {
    return '--'
  }
}

/* 文件上传 */
const handleAvatarSuccess = (res, contractId) => {
  if (res.code === 200) {
    console.log(res)
    // 这里可以根据后端返回的数据更新合同信息
    // 例如：updateContract({ id: contractId, fileUrl: res.data.url })
    ElMessage.success("文件上传成功");

    // 如果需要更新表格数据，可以重新加载列表
    getList();
  } else {
    ElMessage.error(res.msg);
  }
};

const beforeAvatarUpload = (rawFile) => {
  const fileExt = rawFile.name.split('.').pop().toLowerCase();
  const allowedExts = ['doc', 'docx', 'pdf'];

  if (!allowedExts.includes(fileExt)) {
    ElMessage.error('仅支持 doc、docx、pdf 格式的文件');
    return false;
  }

  if (rawFile.size / (1024 * 1024) > 2) {
    ElMessage.error('文件大小不能超过 2MB');
    return false;
  }

  return true;
}
</script>

<style scoped>
/* 布局样式 */
.layout-row {
  display: flex;
  gap: 20px;
  padding: 20px;
}

.left-tree {
  width: 220px;
  border-right: 1px solid #e4e7ed;
}

.tree-header {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 15px;
}

.right-content {
  flex: 1;
}

.top-bar {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}

.search-input {
  width: 240px;
}

.mb8 {
  margin-bottom: 8px;
}

/* 操作栏按钮样式优化 */
.operation-column {
  white-space: nowrap;
}

.operation-btn {
  padding: 0 6px;
  margin-right: 4px;
  display: inline-flex;
  align-items: center;
  transition: all 0.2s;
  height: 24px;
  border-radius: 3px;
}

.edit-btn {
  color: #409eff;
}

.edit-btn:hover {
  color: #66b1ff;
  background-color: #e6f7ff;
}

.delete-btn {
  color: #f56c6c;
}

.delete-btn:hover {
  color: #f78989;
  background-color: #fef0f0;
}

.upload-btn {
  color: #67c23a;
}

.upload-btn:hover {
  color: #85ce61;
  background-color: #f0f9eb;
}

.download-btn {
  color: #e6a23c;
}

.download-btn:hover {
  color: #ebb563;
  background-color: #fdf6ec;
}

/* 上传组件样式微调 */
.operation-column .el-upload {
  display: inline-flex !important;
  align-items: center;
  margin-right: 4px;
  padding: 0 6px;
  height: 24px;
  border-radius: 3px;
}

.operation-column .el-upload--text {
  color: #67c23a;
}

.operation-column .el-upload--text:hover {
  color: #85ce61;
  background-color: #f0f9eb;
}

/* 隐藏上传后显示的文件名 */
.operation-column .el-upload-list {
  display: none !important;
}
</style>